package config

import (
	"encoding/json"
	"io/ioutil"
	"log"
)

// make a copy of this file, rename to settings.go
// then set the correct value for these follow variables
var (
	LogFile = ""
	Daemon  = ""

	EmailServerAddr = ""
	EmailUserName   = ""
	EmailPassword   = ""
	From            = ""
	Tos             = ""

	Account  = ""
	Password = ""

	DevServerUrl  = ""
	UserServerUrl = ""
)

func ParseConfigFile(filepath string) bool {
	type Params struct {
		LogFile string `json:"log_file"`
		Daemon  string `json:"daemon"`

		EmailServerAddr string `json:"email_server_addr"`
		EmailUserName   string `json:"email_user_name"`
		EmailPassword   string `json:"email_password"`
		From            string `json:"from"`
		Tos             string `json:"tos"`

		Account  string `json:"account"`
		Password string `json:"password"`

		DevServerUrl  string `json:"dev_server_url"`
		UserServerUrl string `json:"user_server_url"`
	}

	data, err := ioutil.ReadFile(filepath)
	if err != nil {
		log.Println("read configure file error:", err)
		return false
	}

	var params = &Params{}
	err = json.Unmarshal(data, params)
	if err != nil {
		log.Println("json un-marshal error:", err)
		return false
	}

	log.Println("-------------------Configure params are:-------------------")
	log.Println(params)

	if params.LogFile != "" {
		LogFile = params.LogFile
	}

	if params.Daemon != "" {
		Daemon = params.Daemon
	}

	if params.EmailServerAddr != "" {
		EmailServerAddr = params.EmailServerAddr
	}

	if params.EmailUserName != "" {
		EmailUserName = params.EmailUserName
	}

	if params.EmailPassword != "" {
		EmailPassword = params.EmailPassword
	}

	if params.From != "" {
		From = params.From
	}

	if params.Tos != "" {
		Tos = params.Tos
	}

	if params.Account != "" {
		Account = params.Account
	}

	if params.Password != "" {
		Password = params.Password
	}

	if params.DevServerUrl != "" {
		DevServerUrl = params.DevServerUrl
	}

	if params.UserServerUrl != "" {
		UserServerUrl = params.UserServerUrl
	}

	return true
}
